import subprocess
import shutil
import os.path
import sys
import os
from scipy.io import wavfile

class Conversion:

    def __init__(self):
        if not os.path.exists("../audio/"):
            os.makedirs("../audio/")

    def convertFile(self, location):
        print location
        output = self.checkFile(location)
        if output == None:
            #return self.checkFile(location)
            oldname = os.path.split(location)[1]
            newname = os.path.splitext(oldname)[0]
            applicationFile = os.path.normpath(os.path.join(os.path.dirname(__file__), "../external/mpg123.exe"))
            outputFile = os.path.normpath(os.path.join(os.path.dirname(__file__), "../audio/%s.wav" % newname))
            print location
            print outputFile
            if subprocess.call([applicationFile, "-qm", "-r", "44100", "-w", outputFile, location]) == 1:
                print "File Type not Supported"
                return None
            else:
                return outputFile
        else:
            return output

    def checkFile(self, location):
        oldname = os.path.split(location)[1]
        newname = os.path.splitext(oldname)[0]
        outputFile = os.path.normpath(os.path.join(os.path.dirname(__file__), "../audio/%s.wav" % newname))
        if location != outputFile:
            return self.sndFileConvert(location, outputFile)
        else:
            return location

    def sndFileConvert(self, location, outputFile):
        applicationFile = os.path.normpath(os.path.join(os.path.dirname(__file__), "../external/sndfile-convert.exe"))
        print applicationFile
        print location
        print outputFile
        if subprocess.call([applicationFile, "-override-sample-rate=44100", "-pcm16", location, outputFile]) == 1:
            print "File Type not Supported"
            return None
        else:
            return outputFile
